﻿using System;
using System.Collections.Generic;
using System.Text;

namespace SharpSoft.Geometries
{
    /// <summary>
    /// 线段
    /// </summary>
    public struct Line2D
    {
        public Line2D(Point2D p1, Point2D p2)
        {
            this.P1 = p1;
            this.P2 = p2;
        }
        public Point2D P1 { get; set; }
        public Point2D P2 { get; set; }
        /// <summary>
        /// 获取线段的长度
        /// </summary>
        public double Length
        {
            get
            {
                return Line2D.GetLength(this.P1, this.P2);
            }
        }
        /// <summary>
        /// 获取两点之间的线段长度
        /// </summary>
        /// <param name="p1"></param>
        /// <param name="p2"></param>
        /// <returns></returns>
        public static double GetLength(Point2D p1, Point2D p2)
        {
            return Math.Sqrt((p2.X - p1.X).Pow() + (p2.Y - p1.Y).Pow());
        }
        /// <summary>
        /// 获取点到线段的最短距离
        /// </summary>
        /// <param name="line_p1">线段起始点</param>
        /// <param name="line_p2">线段终结点</param>
        /// <param name="p">测算点</param>
        /// <returns></returns>
        public static double GetMinDistanse(Point2D line_p1, Point2D line_p2, Point2D p)
        {
            Trigon2D trigon = new Trigon2D(p, line_p1, line_p2);
            var angle1 = trigon.GetAngle(2);
            var angle2 = trigon.GetAngle(3);

            var angle_90 = new Radian(Math.PI / 2d);
            if (angle1 > angle_90)
            {//三角形P2为钝角，直接获取两点间距
                return Line2D.GetLength(p, line_p1);
            }
            else if (angle2 > angle_90)
            {//三角形P3为钝角，直接获取两点间距
                return Line2D.GetLength(p, line_p2);
            }
            else
            {//获取三角形P1对应的高
                return trigon.GetHeight(1);
            }

        }

    }
}
